package com.lingshi.shopping_order_service.rocketmq;

import cn.hutool.core.date.DateUtil;
import com.lingshi.shopping.constant.Constant;
import com.lingshi.shopping.entity.Orders;
import com.lingshi.shopping.enums.OrderStatusEnums;
import com.lingshi.shopping.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Component
@RocketMQMessageListener(topic = Constant.CHECK_ORDER_STATUS_TOPIC,
        consumerGroup = Constant.CHECK_ORDER_STATUS_CONSUMER_GROUP
)
public class CheckOrdersListener implements RocketMQListener<String> {

    @Autowired
    private OrdersService ordersService;

    @Override
    public void onMessage(String orderId) {

        log.info("rocketMQ： {}", orderId);
        Orders orders = ordersService.findById(orderId);
        //未支付状态才关闭订单
        if(Objects.nonNull(orders) && OrderStatusEnums.UNPAID.getCode().equals(orders.getStatus())){
            //订单过期时间
            Date expire = orders.getExpire();
            //当前时间
            Date now = new Date();

            if (DateUtil.compare(now, expire) > 0) {
                //关闭订单
                orders.setStatus(OrderStatusEnums.CLOSED.getCode());
                ordersService.update(orders);
                //TODO 回退库存
            }

        }

    }
}
